<?php

namespace app\common\model\lottery;

use app\common\library\helper;
use app\common\model\BaseModel;
use app\common\model\lottery\Active;
use app\common\model\lottery\Goods as GoodsModel;

/**
 * 抽奖指定商品
 * @package app\common\model\lottery
 */
class ActiveGoods extends BaseModel
{
    protected $name = 'lottery_active_goods';

    /**
     * 关联活动会场表
     */
    public function active()
    {
        return $this->belongsTo(Active::class, 'active_id');
    }

    /**
     * 
     */
    public function goods()
    {
        return $this->belongsTo(GoodsModel::class, 'lottery_goods_id');
    }


    protected function getGoodsModel()
    {
        return new GoodsModel;
    }

    /**
     * 计算商品销售进度
     * @param $value1
     * @param $value2
     * @return mixed
     */
    protected function getProgress($value1, $value2)
    {
        if ($value2 <= 0){
            return 100;
        }
        $progress = helper::bcdiv($value1, $value2);
        return min(100, (int)helper::bcmul($progress, 100, 0));
    }


     /**
     * 活动ID获取商品列表
     */
    public static function getGoodsListByActiveId($active_id)
    {
        $model = new static;
        $activeGoodsList = $model->getLotteryGoodsByActiveId($active_id);
        // 将列表的索引值设置为商品ID
        $activeGoodsList = helper::arrayColumn2Key($activeGoodsList, 'lottery_goods_id');
        // 获取商品列表
        $sharpGoodsList = $model->getGoodsListByIds(array_keys($activeGoodsList), []);
        // 整理活动商品信息
        foreach ($sharpGoodsList as &$item) {
            // 活动商品的销量
            $item['sales_actual'] = $activeGoodsList[$item['lottery_goods_id']]['sales_actual'];
            // 商品销售进度
            $item['progress'] = $model->getProgress($item['sales_actual'], $item['stock_nums']);
        }
       return $sharpGoodsList->hidden(['sku', 'goods']);
    }

    private function getGoodsListByIds($sharpGoodsIds, $param = [])
    {
        return $this->getGoodsModel()->getListByIds($sharpGoodsIds, $param);
    }

    /**
     * 
     */
    private function getLotteryGoodsByActiveId($active_id)
    {
        return $this->where('active_id', '=', $active_id)->select();
    }


}